package com.sz.lk.wingsystem.mvp.model;


import com.google.gson.Gson;
import com.sz.lk.wingsystem.bean.LoginPamars;
import com.sz.lk.wingsystem.bean.LoginResult;
import com.sz.lk.wingsystem.mvp.BaseRequest;
import com.sz.lk.wingsystem.mvp.MRequestBody;
import com.sz.lk.wingsystem.mvp.OnNetRequestListener;
import com.sz.lk.wingsystem.mvp.RxPresenter;
import com.sz.lk.wingsystem.mvp.contract.LoginContract;
import com.sz.lk.wingsystem.mvp.rxuntils.RxScheduler;
import com.sz.lk.wingsystem.mvp.rxuntils.Subscribe2Help;

import io.reactivex.Observable;
import okhttp3.RequestBody;

public class LoginModel extends BaseRequest implements LoginContract.Model {
    public LoginModel(RxPresenter mRxPresenter) {
        super(mRxPresenter);
    }

    @Override
    public void Login(String name, String pass, OnNetRequestListener<LoginResult> listener) {
        //如果是异步操作就把返回的Disposable 取出 添加; charset=UTF-8

        //Charset.forName("UTF-8")
        RequestBody requestBody = null;
        try {
            requestBody = MRequestBody.create(okhttp3.MediaType.parse("application/json"),
                    new Gson().toJson(new LoginPamars(name, pass)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Observable<LoginResult> observable = webRequest.login(requestBody);
        listener.onStart();
        observable.compose(RxScheduler.<LoginResult>Obs_io_main())

                .subscribe(new Subscribe2Help<LoginResult>(mRxPresenter) {
                    @Override
                    public void onNext(LoginResult value) {
                        listener.onSuccess(value);
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        listener.onFailure(throwable);
                    }

                    @Override
                    public void onComplete() {
                        listener.onFinish();
                    }
                });
    }
}
